package com.ccrfid.rmc6.service.device;

import com.ccrfid.rmc6.entity.device.LocatorEntity;
import com.ccrfid.rmc6.pojo.amq.AmqLocator;
import com.ccrfid.rmc6.service.amq.MqMsgProducer;
import com.ccrfid.rmc6.util.JsonUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class LocatorServiceAspect {
    private static final Logger logger = LoggerFactory.getLogger(LocatorServiceAspect.class);
    @Autowired
    private MqMsgProducer mqMsgProducer;

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.device.LocatorService.createLocator(..))",
            returning = "ret")
    public void afterCreateLocator(LocatorEntity ret) {
        AmqLocator msgLocator = new AmqLocator(ret.getId(), ret.getLocatorAddress(), ret.getEnabled());
        String msg = JsonUtil.INSTANCE.writeValueAsString(msgLocator);
        mqMsgProducer.send2Topic("ws_locator_add", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.device.LocatorService.updateLocator(..))",
            returning = "ret")
    public void afterUpdateLocator(LocatorEntity ret) {
        AmqLocator msgLocator = new AmqLocator(ret.getId(), ret.getLocatorAddress(), ret.getEnabled());
        String msg = JsonUtil.INSTANCE.writeValueAsString(msgLocator);
        mqMsgProducer.send2Topic("ws_locator_update", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.device.LocatorService.deleteLocatorsInfo(..)) && args(idList)",
            argNames = "idList")
    public void afterDeleteLocators(List<Long> idList) {
        String msg = JsonUtil.INSTANCE.writeValueAsString(idList);
        mqMsgProducer.send2Topic("ws_locator_delete", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.device.LocatorService.updatePosition(..))",
            returning = "ret")
    public void afterUpdateLocatorPosition(LocatorEntity ret) {
        AmqLocator msgLocator = new AmqLocator(ret.getId(), ret.getLocatorAddress(), ret.getEnabled());
        String msg = JsonUtil.INSTANCE.writeValueAsString(msgLocator);
        mqMsgProducer.send2Topic("ws_locator_position_update", msg);
    }

    @AfterReturning(value = "execution(public * com.ccrfid.rmc6.service.device.LocatorService.deletePosition(*))",
            returning = "ret")
    public void afterDeleteLocatorPosition(LocatorEntity ret) {
        AmqLocator msgLocator = new AmqLocator(ret.getId(), ret.getLocatorAddress(), ret.getEnabled());
        String msg = JsonUtil.INSTANCE.writeValueAsString(msgLocator);
        mqMsgProducer.send2Topic("ws_locator_position_delete", msg);
    }
}
